<template>
  <div class="fenghuang">
    <div class="fenghuang-header"  @keyup.enter="search">
      <div class="info">
        <div>凤凰网热榜</div>
        <div>内容偏重于军事</div>
      </div>
      <el-radio-group v-model="searchMethod" >
        <el-radio label="byWord" size="large">按关键字查询</el-radio>
        <el-radio label="byTime" size="large">按时间段查询</el-radio>
      </el-radio-group>
      <div class="input-wrapper">
        <el-date-picker
          v-if="searchMethod == 'byTime'"
          v-model="timeRange"
          type="datetimerange"
          :shortcuts="shortcuts"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
        <el-input 
          :maxlength="20"
          show-word-limit
          type="text"
          v-if="searchMethod == 'byWord'"
          placeholder="请输入关键字"
          v-model="hotWord"
        />
      </div>
      <el-button type="primary" @click="search">查询</el-button>
    </div>
    <div class="fenghuang-result" ref="resultDiv">
      <el-table :data="hotsInCurrentPage" style="width: 100%" empty-text="无数据">
        <el-table-column prop="hotWord"  width="350" >
          <template v-slot="props">
            <el-tooltip effect="dark" :content="props.row.title || '无相关描述'" placement="top-start">
              <a :href="getUrlByFengHuangId(props.row.id)" target="blank">{{ props.row.word }}</a>
            </el-tooltip>
          </template>
          <template #header>
            热搜词条
          </template>
        </el-table-column>
        <el-table-column prop="times">
          <template #header>
            在榜时长（分钟）
            <el-tooltip effect="dark" content="按该列进行升序/降序排序" placement="top-start">
              <el-icon @click="sortByTimes"><Sort /></el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="firstTime"  >
          <template v-slot="props">
            {{ formatTime(props.row.firstTime) }}
          </template>
          <template #header>
            初次上榜时间
            <el-tooltip effect="dark" content="按该列进行升序/降序排序" placement="top-start">
              <el-icon @click="sortByFirstTime"><Sort /></el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="lastTime"  >
          <template v-slot="props">
            {{ formatTime(props.row.lastTime) }}
          </template>
          <template #header>
            最后在榜时间
          </template>
        </el-table-column>
        <el-table-column prop="topRank" >
          <template #header>
            最高排名
            <el-tooltip effect="dark" content="按该列进行升序/降序排序" placement="top-start">
              <el-icon @click="sortByTopRank"><Sort /></el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="bottomRank"  >
          <template #header>
            最低排名
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="fenghuang-bottom">
      <el-pagination 
        background 
        layout="prev, pager, next" 
        :total="total" 
        :pager-count="pagerCount" 
        :page-size="pageSize"
        v-model:current-page="currentPage"
      />
      <!-- 这里必须要使用v-model:current-page双向绑定，不写v-model的用法已经被废弃，官网文档没更新 -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { usePagination, useSearchOption, useSortFlag } from '../../hook/hot';
import { Debounce, Throttle, toDebounce } from '../../util/excuteFunc';
import { formatTime } from '../../util/chore';
import { computed, onActivated, onMounted, ref, Ref } from 'vue';
import { BaiduHot, FengHuangHot } from '../../type/entity';
import { getBaiduHotByTime, getBaiduHotByWord, getFengHuangHotByTime, getFengHuangHotByWord } from '../../request/hot';
import { ElMessage } from 'element-plus';
const resultDiv = ref() as Ref<HTMLDivElement>
const {searchMethod, timeRange, shortcuts, hotWord} = useSearchOption()
const hots = ref([]) as Ref<FengHuangHot[]>
const {total, pageSize, pagerCount, currentPage} = usePagination(hots)
const {topRankSort, firstTimeSort, timesSort} = useSortFlag()
const hotsInCurrentPage = computed(() => {
  let startIndex = (currentPage.value - 1) * pageSize.value
  let endIndex = startIndex + pageSize.value
  return hots.value.slice(startIndex, endIndex)
})
function searchByWord(){
  if(hotWord.value == ''){
    ElMessage({type: 'warning', message: '输入不能为空'})
    return
  }
  getFengHuangHotByWord(hotWord.value).then(
    val => {
      hots.value = val.data
      ElMessage({type: 'success', message: '查询到' + hots.value.length + '条记录'})
    }
  )
}
function searchByTime(){
  getFengHuangHotByTime(timeRange.value[0].getTime(), timeRange.value[1].getTime()).then(
    val => {
      hots.value = val.data
      ElMessage({type: 'success', message: '查询到' + hots.value.length + '条记录'})
    }
  )
}
let searchThrottle:Throttle
function search(){
  if(!searchThrottle){
    searchThrottle = new Throttle(() => {
      if(searchMethod.value == 'byWord'){
        searchByWord()
      }
      else if (searchMethod.value == 'byTime'){
        searchByTime()
      }
    }, 2000)
  }
  searchThrottle.excute()
}
function sortByFirstTime(){
  hots.value.sort((hot1, hot2) => (hot1.firstTime - hot2.firstTime) * firstTimeSort.value)
  firstTimeSort.value *= -1
}
function sortByTopRank(){
  hots.value.sort((hot1, hot2) => (hot1.topRank - hot2.topRank) * topRankSort.value)
  topRankSort.value *= -1
}
function sortByTimes(){
  hots.value.sort((hot1, hot2) => (hot1.times - hot2.times) * timesSort.value)
  timesSort.value *= -1
} 
function getUrlByFengHuangId(id:string){
  if(id.startsWith('ucms_')){
    return `https://ishare.ifeng.com/c/s/${id.slice(5)}`
  }
  else{
    return `https://ishare.ifeng.com/c/s/${id}`
  }
}
const resize = toDebounce(() => {
  let height = resultDiv.value.offsetHeight
  pageSize.value = Math.floor((height - 65) / 40)
}, 100)
onActivated(() => {
  resize()
})
onMounted(() => {
  window.addEventListener('resize', () => {
    resize()
  })
})
</script>

<style scoped>

</style>